package com.tanhua.server.controller;

import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ResultVo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserInfoService;

import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserService userService;

    /*用户资料---读取*/
    @GetMapping
    public ResponseEntity users(Long userID) {
        //判断ID
        if (userID == null) {
            //用户id为空则使用当前登录的用户id
            userID = UserHolder.getUserId();
        }
        //调用service进行查询
        UserInfoVo userInfoVo = userInfoService.findById(userID);
        return ResponseEntity.ok(userInfoVo);
    }

    /*用户资料---保存(更新)*/
    @PutMapping
    public ResponseEntity updateUserInfo(@RequestBody UserInfo userInfo) {
        //添加需要更新的用户ID
        userInfo.setId(UserHolder.getUserId());
        //调用service进行更新操作
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);
    }

    /*修改手机号- 1 发送短信验证码*/
    @PostMapping("/phone/sendVerificationCode")
    public ResponseEntity sendMessage() {
        final String phone = UserHolder.getMobile();
        userService.sendMsg(phone);
        return ResponseEntity.ok(null);
    }

    /*修改手机号 - 2 校验验证码*/
    @PostMapping("/phone/checkVerificationCode")
    public ResponseEntity checkVerificationCode(@RequestBody Map map) {
        String code = (String) map.get("verificationCode");
        ResultVo vo = userService.checkVerificationCode(code);
        return ResponseEntity.ok(vo);
    }

    /*修改手机号 - 3 保存*/
    @PostMapping("/phone")
    public ResponseEntity updatePhone(@RequestBody Map map){
        String phone = (String) map.get("phone");
        userService.updatePhone(phone);
        return ResponseEntity.ok(null);
    }

    /*用户资料 - 更新头像*/
    @PostMapping("/header")
    public ResponseEntity updateHeader(MultipartFile headPhoto)throws IOException {
        userInfoService.updateHead(headPhoto);
        return ResponseEntity.ok(null);
    }
}

